package my.common.util.http;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import my.common.util.http.bean.ResponseBean;


public class HttpUtils {
    public static ResponseBean sendGet(String url, Map<String, String> headers, String bodyParam) {
        String result = "";
        BufferedReader in = null;
        int respCode = 0;
        HttpURLConnection connection = null;
        try {
            String urlNameString = url + "?" + bodyParam;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            connection = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            for (Entry<String, String> header : headers.entrySet()) {
                connection.setRequestProperty(header.getKey(), header.getValue());
            }
            // connection.setRequestProperty("accept", "*/*");
            // connection.setRequestProperty("connection", "Keep-Alive");
            // connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE
            // 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // connection.setDoOutput(true);
            // 获取所有响应头字段
            /*
			 * Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段
			 * for (String key : map.keySet()) { System.out.println(key + "--->" +
			 * map.get(key)); }
			 */
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            respCode = connection.getResponseCode();
        } catch (FileNotFoundException e) {
            ResponseBean responseBean = new ResponseBean();
            responseBean.setReturnCode(404);
            return responseBean;
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (connection != null) {
                    connection.disconnect();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        ResponseBean responseBean = new ResponseBean();
        responseBean.setReturnStr(result);
        responseBean.setReturnCode(respCode);
        return responseBean;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static ResponseBean sendPost(String url, Map<String, String> headers, String bodyParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        int respCode = 0;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            for (Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
            // conn.setRequestProperty("accept", "*/*");
            // conn.setRequestProperty("connection", "Keep-Alive");
            // conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;
            // Windows NT 5.1;SV1)");
            // conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(bodyParam);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            respCode = conn.getResponseCode();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        ResponseBean responseBean = new ResponseBean();
        responseBean.setReturnStr(result);
        responseBean.setReturnCode(respCode);
        return responseBean;
    }

    public static ResponseBean sendPut(String url, Map<String, String> headers, String bodyParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        int respCode = 0;
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            for (Entry<String, String> header : headers.entrySet()) {
                conn.setRequestProperty(header.getKey(), header.getValue());
            }
            // conn.setRequestProperty("accept", "*/*");
            // conn.setRequestProperty("connection", "Keep-Alive");
            // conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;
            // Windows NT 5.1;SV1)");
            // conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("PUT");
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(bodyParam);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            respCode = conn.getResponseCode();
        } catch (Exception e) {
            System.out.println("发送 PUT 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        ResponseBean responseBean = new ResponseBean();
        responseBean.setReturnStr(result);
        responseBean.setReturnCode(respCode);
        return responseBean;
    }

    public static Map<String, String> getCommonHeaders() {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept", "*/*");
        headers.put("connection", "Keep-Alive");
        headers.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        headers.put("Content-Type", "application/json");
        return headers;
    }
}
